package cn.demo.thread;

/**
 * 多线程通信
 *
 * @author duxiaod
 * @date 2021/07/24 19:26
 **/
public class TwoThreadWaitNotify {

    private int start = 1;
    private boolean flag = false;

    public static void main(String[] args) {
        TwoThreadWaitNotify twoThread = new TwoThreadWaitNotify();
        Thread t1 = new Thread(new OuThread(twoThread),"A");
        Thread t2 = new Thread(new JiThread(twoThread),"B");

        t1.start();
        t2.start();
    }

    /**
     * 偶数线程
     */
    public static class OuThread implements Runnable{

        private TwoThreadWaitNotify number;

        public OuThread(TwoThreadWaitNotify number){
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <= 100){
                synchronized (TwoThreadWaitNotify.class){
                    System.out.println("偶数数线程抢到了锁");
                    if(number.flag){
                        System.out.println(Thread.currentThread().getName()+"偶数"+number.start);
                        number.start++;
                        number.flag = false;
                        TwoThreadWaitNotify.class.notify();
                    }else {
                        try {
                            TwoThreadWaitNotify.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    /**
     * 奇数线程
     */
    public static class JiThread implements Runnable{
        private TwoThreadWaitNotify number;

        public JiThread(TwoThreadWaitNotify number){
            this.number = number;
        }
        @Override
        public void run() {
            while (number.start <= 100){
                synchronized (TwoThreadWaitNotify.class){
                    System.out.println("奇数线程抢到了锁");
                    if(!number.flag){
                        System.out.println(Thread.currentThread().getName()+"奇数"+number.start);
                        number.start++;
                        number.flag = true;
                        TwoThreadWaitNotify.class.notify();
                    }else {
                        try {
                            TwoThreadWaitNotify.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
